package com.leha.mp.api.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.*;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.leha.mp.api.form.OrderForm;
import com.leha.mp.core.Utils.IpUtil;
import com.leha.mp.core.entity.mybatis.PlOrder;
import com.leha.mp.core.entity.vo.ConsultingVO;
import com.leha.mp.core.services.*;
import com.leha.utils.DateTool;
import constants.APIErrorDict;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.APIResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.QueryParam;
import java.util.Date;

@RestController
@RequestMapping("/order")
@Log4j2
public class OrderController {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private WAppServices wAppServices;
  @Autowired
  private OrderServices orderServices;
  @Autowired
  private AppUserService userService;
  @Autowired
  private AppDoctorServices doctorServices;
  @Autowired
  private ErrorMessageServices errorMessageServices;

  @PostMapping("/genOrder")
  @ApiOperation("生产咨询订单_用户端")
  public APIResult genOrder(HttpServletRequest request, OrderForm orderForm) {

      PlOrder order = orderServices.GenOrder(orderForm.getUserId(),
              orderForm.getDoctorId(), orderForm.getProductId(), IpUtil.getIp(request),
              orderForm.getExtraData());
      if(order == null) {
          return new APIResult(errorMessageServices.getLastError());
      }
      try{
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody(order.getOrderBody());
        orderRequest.setOutTradeNo(order.getOrderNo());
        orderRequest.setTotalFee(order.getOrderFee());//元转成分
        orderRequest.setOpenid(userService.getOpenId(orderForm.getUserId()));
        orderRequest.setSpbillCreateIp(order.getUserIp());
        orderRequest.setTimeStart(DateTool.formatDate(new Date(), "yyyyMMddHHmmss"));
        orderRequest.setTimeExpire(DateTool.formatDate(DateTool.MinisOp(new Date(), 30), "yyyyMMddHHmmss"));
        WxPayMpOrderResult res = wAppServices.getPayServices().createOrder(orderRequest);
        ConsultingVO vo = new ConsultingVO();
        vo.setData(res);
        vo.setConsultingId(orderServices.getOrderConsulting(order.getOrderId()));
        return new APIResult(vo);
      } catch (WxPayException e) {
        return new APIResult(APIErrorDict.WXPAYERROR);
      }
  }

  @PostMapping("/wxcb")
  @ApiOperation("微信callback")
  public APIResult payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            log.info("callback res:"+xmlResult);
            WxPayOrderNotifyResult result = wAppServices.getPayServices().parseOrderNotifyResult(xmlResult);
            // 结果正确
            String orderNo = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            orderServices.OrderPaySuccess(orderNo, new Date(), tradeNo, result.getResultCode(), result.getErrCode());
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            return new APIResult("OK");
        } catch (Exception e) {
            log.error("callback res:"+e.getMessage());
            return new APIResult(e.getMessage());
        }
    }

    @GetMapping("/{doctorId}")
    @ApiOperation("医生订单_医生端")
    public APIResult getDoctorOrder(@PathVariable Integer doctorId, @QueryParam(value="type") Integer type) {
      return new APIResult(doctorServices.getDoctorOrders(doctorId, type));
    }

    @PostMapping("/cancelOrder")
    @ApiOperation("取消订单_用户端")
    public APIResult cancelOrder(@FormParam(value="userId") Integer userId, @FormParam(value="orderId") Integer orderId) {
      return new APIResult(orderServices.cancelOrder(userId, orderId));
    }

    @PostMapping("/wxrefundcb")
    @ApiOperation("微信退款回调")
    public APIResult refundNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            log.info("refundNotify res:"+xmlResult);
            WxPayRefundNotifyResult result = wAppServices.getPayServices().parseRefundNotifyResult(xmlResult);
            // 结果正确
            String refundNo = result.getReqInfo().getOutRefundNo();
            String tradeNo = result.getReqInfo().getOutTradeNo();
            orderServices.OrderRefundSuccess(refundNo, result.getReturnCode(), result.getErrCode());
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            return new APIResult("OK");
        } catch (Exception e) {
            log.error("callback res:"+e.getMessage());
            return new APIResult(e.getMessage());
        }
    }

    @GetMapping("/{orderId}/detail")
    @ApiOperation("订单详情")
    public APIResult getOrderDetail(@PathVariable Integer orderId) {
      return new APIResult(orderServices.getOrderDetail(orderId));
    }
}

